package org.swim.session;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;
import org.swim.entity.Notification;
import org.swim.entity.User;

@Stateless
@RemoteBinding(jndiBinding="NotificationManagerRemote")
public class NotificationManager implements NotificationManagerRemote {
	
	/**
	 * Manager degli entity beans. Permette di interagire direttamente col database inserendo e ricercando dati
	 */
	@PersistenceContext(unitName="swim") private EntityManager manager;
	
	
	@Override
	public Notification createNotification(String text, int recipientID, int senderID) {
		
		Notification toCreate= new Notification();
		
		try {
			User rec=manager.find(User.class, recipientID);
			User sen=manager.find(User.class, senderID);
			
			toCreate.setRecipient(rec);
			toCreate.setSender(sen);
			toCreate.setText(text);
			
			return toCreate;
			
		} catch (NullPointerException e) {
			return null;
		}

		
	}

	@Override
	public List<Notification> getAllNotificationByUser(int userID) {
		
		List<Notification> result = new ArrayList<Notification>();
		
		try 
		{
			Query q = manager.createQuery("SELECT OBJECT(no) FROM Notification AS no" +
											"WHERE no.getRecipient().getId=:ID");
			q.setParameter("ID", userID);

			
			
			@SuppressWarnings("unchecked")
			Collection<Notification> coll = (Collection<Notification>) q.getResultList();

			Iterator<Notification> itar = coll.iterator();
			
			while (itar.hasNext())
			{	
				result.add(itar.next());
			}
			
		} 
		catch (EntityNotFoundException exc){} 
		
		return result;		
		
	}

	@Override
	public void deleteAllNotificationByUser(int userID) {
		
		try 
		{
			User RECIPIENT=manager.find(User.class, userID);

			Query q = manager.createQuery("SELECT OBJECT(no) FROM Notification AS no" +
											"WHERE no.recipient=:U");
			q.setParameter("U", RECIPIENT);

			
			
			@SuppressWarnings("unchecked")
			Collection<Notification> coll = (Collection<Notification>) q.getResultList();

			Iterator<Notification> itar = coll.iterator();
			
			while (itar.hasNext())
			{	
				manager.remove(itar.next());
			}
			
		} 
		catch (EntityNotFoundException exc){} 
		
	}

	@Override
	public void deleteNotification(int notificationID) {
		
		Notification n=manager.find(Notification.class, notificationID);
		
		manager.remove(n);
		
	}
	
	

}
